/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.listener;

import cn.easyplatform.messages.request.SimpleRequestMessage;
import cn.easyplatform.messages.vos.EnvVo;
import cn.easyplatform.spi.service.ApplicationService;
import cn.easyplatform.type.Constants;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.web.WebApps;
import cn.easyplatform.web.contexts.Contexts;
import cn.easyplatform.web.service.ServiceLocator;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Desktop;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.sys.DesktopCtrl;
import org.zkoss.zk.ui.sys.SessionCtrl;
import org.zkoss.zkmax.zul.Drawer;
import org.zkoss.zul.Timer;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class SessionValidationScheduler implements EventListener<Event> {

    private String sessionId;

    public static void start(final Component parent) {
        new SessionValidationScheduler(parent);
    }

    @SuppressWarnings("unchecked")
    private SessionValidationScheduler(Component parent) {
        Desktop desktop = parent.getDesktop();
        Timer timer = new Timer();
        timer.setParent(parent);
        timer.addEventListener(Events.ON_TIMER, this);
        timer.setRepeats(true);
        timer.setDelay(WebApps.me().getSessionInterval());
        timer.setWidgetOverride("_tmfn","function(){if(!this._repeats)this._running=false;this.fire('onTimer',null,{ignorable:true,forceAjax:true,rtags:{onTimer:1}})}");
        timer.start();
        sessionId = (String) desktop.getSession().getAttribute(Constants.SESSION_ID);
        //自动添加drawer
        Component drawer = parent.query("drawer");
        if (drawer == null) {
            drawer = new Drawer();
            parent.appendChild(drawer);
        }
        drawer.setId("__drawer__");
        ((Drawer) drawer).setClosable(false);
    }

    @Override
    public void onEvent(Event event) throws Exception {
        ApplicationService ac = ServiceLocator.lookup(ApplicationService.class);
        SimpleRequestMessage req = new SimpleRequestMessage();
        req.setSessionId(sessionId);
        IResponseMessage<?> resp = ac.ttl(req);
        if (!resp.isSuccess()) { // 如果心跳返回错误，直接停止
            if ("E000".equals(resp.getCode())) {
                EnvVo env = Contexts.getEnv();
                if (env != null)
                    LogoutListener.logout(env);
            }
            ((Timer) event.getTarget()).stop();
        }
    }
}
